package com.axialproject.health.exchange.google;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.http.AuthSubUtil;
import com.axialproject.health.exchange.EMF;
import com.axialproject.health.exchange.PatientManager;
import com.axialproject.health.exchange.entity.Patient;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class AfterLoginServlet extends HttpServlet {

    private static final Logger log = Logger.getLogger(AfterLoginServlet.class.getName());

    public void doGet (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

        String appUrl = this.getServletContext().getInitParameter("AppUrl");

        HttpSession session = req.getSession();
        String finishUrl = (String) session.getAttribute("finishUrl");
        Long patientId = (Long) session.getAttribute("patientId");

        /*
        // Need to validate the sig -- probably need providerName here ...
        String sig = req.getParameter("sig");

        String finishUrl = req.getParameter("finishUrl");
        if (finishUrl == null) {
            finishUrl = "";
        }

        Long patientId = Long.parseLong(req.getParameter("patientId"));
        if (patientId == null) {
            log.severe("Missing patientId");
            return;
        }
        */

        Patient gpatient = new Patient ();

        EntityManager em = EMF.get().createEntityManager();
        try {
            UserService userService = UserServiceFactory.getUserService();
            User user = userService.getCurrentUser();
            if (user == null) {
                throw new Exception ("This servlet must be invoked after a successful Google login!");
            }

            // Create a new gpatient account for each reg attempt.
            // If the user does not confirm, we will have an orphaned gpatient w/o token
            gpatient.setUsername (user.getEmail());
            gpatient.setEmail (user.getEmail());
            gpatient.setAppName("google");
            PatientManager.savePatient(em, gpatient);

            /*
            Patient gpatient = PatientManager.getPatientByUsernameAppName(em, user.getEmail(), "google");
            if (gpatient == null) {
                // Create gpatient in DB
                gpatient = new Patient ();
                gpatient.setUsername (user.getEmail());
                gpatient.setEmail (user.getEmail());
                gpatient.setAppName("google");
                PatientManager.savePatient(em, gpatient);
            }

            // We will restart the process even if the user already has linked Google account -- the user wants to reset for whatever reason

            // send the authUrl with the pass-throu parameters
            String nextUrl = appUrl + "/google/confirm?patientId=" + patientId + "&finishUrl=" + URLEncoder.encode(finishUrl, "UTF-8") + "&sig=1234";
            // String scope = "https://www.google.com/health/feeds/";
            String scope = "https://www.google.com/h9/feeds/";
            boolean secure = false;  // set secure=true to request secure AuthSub tokens
            boolean session = true;
            String authSubUrl = AuthSubUtil.getRequestUrl(nextUrl, scope, secure, session);
            authSubUrl += "&permission=1";
            // authSubUrl = authSubUrl.replaceFirst("/accounts/AuthSubRequest", "/health/authsub");
            authSubUrl = authSubUrl.replaceFirst("/accounts/AuthSubRequest", "/h9/authsub");
            resp.sendRedirect(authSubUrl);
            */
            
        } catch (Exception e) {
            log.log(Level.SEVERE, e.getMessage(), e);
            resp.setContentType("text/plain");
            resp.getWriter().println("There is a problem");
            return;
            
        } finally {
            em.close ();
        }

        if (gpatient.getId() == null) {
            log.severe("EM is closed but gpatient.getId() still returns null. Data store problem??");
            resp.setContentType("text/plain");
            resp.getWriter().println("There is a problem");
            return;
        }

        session.setAttribute ("gpatientId", gpatient.getId());

        String nextUrl = appUrl + "/google/confirm";
        String scope = "https://www.google.com/health/feeds/";
        // String scope = "https://www.google.com/h9/feeds/";
        boolean secure = true;  // set secure=true to request secure AuthSub tokens
        boolean gsession = true;
        String authSubUrl = AuthSubUtil.getRequestUrl(nextUrl, scope, secure, gsession);
        authSubUrl += "&permission=1";
        authSubUrl = authSubUrl.replaceFirst("/accounts/AuthSubRequest", "/health/authsub");
        // authSubUrl = authSubUrl.replaceFirst("/accounts/AuthSubRequest", "/h9/authsub");
        resp.sendRedirect(authSubUrl);

    }

    public void doPost (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        doGet (req, resp);
    }

}
